<template>
  <el-dialog :title="$t('productCenter.userLevel.title')" :visible.sync="showState" :before-close="handleClose" :close-on-click-modal="false" width="80%">
    <el-form ref="formValidate" :model="formValidate" :rules="rules" label-width="200px" class="demo-ruleForm">
      <el-form-item :label="$t('productCenter.userLevel.list.name')" prop="userLevelName">
        <el-input v-model="formValidate.userLevelName" clearable :placeholder="$t('productCenter.userLevel.prompt')" :maxlength="50" />
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.optional')" prop="loanProductIdList">
        <el-select v-model="formValidate.loanProductIdList" multiple clearable :placeholder="$t('productCenter.userLevel.promptProduct')" style="width: 100%" @change="getNotOptional">
          <el-option
            v-for="item in optionalData"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.notOptional')">
        <el-select v-model="formValidate.showLoanProductIdList" multiple clearable :placeholder="$t('productCenter.userLevel.promptProduct')" style="width: 100%" @change="getOptional">
          <el-option
            v-for="item in notOptionalData"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.freeDayInterestRate')">
        <el-input
          v-model="formValidate.freeDayInterestRate"
          :maxlength="10"
          @input="keyup('freeDayInterestRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.freeServiceFeeRate')">
        <el-input
          v-model="formValidate.freeServiceFeeRate"
          :maxlength="10"
          @input="keyup('freeServiceFeeRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.status')" prop="status">
        <el-select v-model="formValidate.status" clearable :placeholder="$t('productCenter.userLevel.promptProduct')" style="width: 100%">
          <el-option
            v-for="item in $t('productCenter.userLevel.state')"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('productCenter.userLevel.list.title')">
        <span>{{ $t('productCenter.userLevel.tips.one') }}</span>
        <span class="left">{{ $t('productCenter.userLevel.tips.two') }}</span><br>
        <span class="left">{{ $t('productCenter.userLevel.tips.three') }}</span>
        <span class="left">{{ $t('productCenter.userLevel.tips.four') }}</span>
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.rState">
            {{ $t('productCenter.userLevel.list.pastSuccessfulBorrowings') }}
          </el-checkbox>
        </template>
        <el-input
          v-model="formValidate.repetitionLoanNum"
          clearable
          :maxlength="20"
          :placeholder="$t('productCenter.userLevel.prompt')"
        />
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.hState">
            {{ $t('productCenter.userLevel.list.historyOverdueNum') }}
          </el-checkbox>
        </template>
        <el-input
          v-model="formValidate.historyOverdueNum"
          clearable
          :maxlength="20"
          :placeholder="$t('productCenter.userLevel.prompt')"
        />
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.lState">
            {{ $t('productCenter.userLevel.list.whetherSettle') }}
          </el-checkbox>
        </template>
        <el-select v-model="formValidate.lastNormalSettle" :placeholder="$t('common.select')" style="width: 100%">
          <el-option
            v-for="item in $t('productCenter.userLevel.type')"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.dState">
            {{ $t('productCenter.userLevel.list.lastOverdueDays') }}
          </el-checkbox>
        </template>
        <el-input
          v-model="formValidate.lastDueDays"
          clearable
          :maxlength="20"
          :placeholder="$t('productCenter.userLevel.prompt')"
        />
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.tState">
            {{ $t('productCenter.userLevel.list.telecomScore') }}
          </el-checkbox>
        </template>
        <el-input
          v-model="formValidate.telecomScore"
          clearable
          :maxlength="20"
          :placeholder="$t('productCenter.userLevel.prompt')"
        />
      </el-form-item>
      <el-form-item>
        <template slot="label">
          <el-checkbox v-model="formValidate.cState">
            {{ $t('productCenter.userLevel.list.creditScore') }}
          </el-checkbox>
        </template>
        <el-input
          v-model="formValidate.creditScore"
          clearable
          :maxlength="20"
          :placeholder="$t('productCenter.userLevel.prompt')"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('common.operate.cancel') }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.operate.sure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUserLevel, addUserLevel } from '@/api/product'
import { div } from '@/utils/method'
export default {
  name: 'UserLevelDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    chooseItem: {
      type: Object,
      default: function() {
        return {}
      }
    },
    loanProductData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      submitLoading: false,
      optionalData: [],
      notOptionalData: [],
      formValidate: {
        id: null,
        userLevelName: null,
        loanProductIdList: [],
        showLoanProductIdList: [],
        freeDayInterestRate: null,
        freeServiceFeeRate: null,
        status: 1,
        rState: false,
        repetitionLoanNum: null,
        hState: false,
        historyOverdueNum: null,
        lState: false,
        lastNormalSettle: null,
        tState: false,
        telecomScore: null,
        cState: false,
        creditScore: null,
        dState: false,
        lastDueDays: null
      },
      rules: {
        userLevelName: [{ required: true, message: this.$t('productCenter.userLevel.list.name') + this.$t('common.null'), trigger: 'blur' }],
        loanProductIdList: [{ required: true, type: 'array', message: this.$t('productCenter.userLevel.list.optional') + this.$t('common.null'), trigger: 'blur' }],
        status: [{ required: true, type: 'number', message: this.$t('productCenter.product.list.state') + this.$t('common.null'), trigger: 'blur' }]
      }
    }
  },
  computed: {
    showState: {
      get: function() {
        return this.showDialog
      },
      set: function() {
      }
    }
  },
  mounted() {
    this.formValidate = this.chooseItem
  },
  methods: {
    getOptional() {
      if (this.formValidate.showLoanProductIdList) {
        this.optionalData = this.loanProductData.filter(v => {
          return !this.formValidate.showLoanProductIdList.includes(v.value)
        })
      } else {
        this.optionalData = this.loanProductData
      }
    },
    getNotOptional() {
      if (this.formValidate.loanProductIdList) {
        this.notOptionalData = this.loanProductData.filter(v => {
          return !this.formValidate.loanProductIdList.includes(v.value)
        })
      } else {
        this.notOptionalData = this.loanProductData
      }
    },
    handleClose() {
      this.$emit('change-dialog', false)
      this.$refs['formValidate'].clearValidate()
    },
    handleSubmit() {
      console.log(this.formValidate)
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const data = {
            id: this.formValidate.id,
            userLevelName: this.formValidate.userLevelName,
            loanProductIdList: this.formValidate.loanProductIdList,
            showLoanProductIdList: this.formValidate.showLoanProductIdList,
            freeDayInterestRate: this.formValidate.freeDayInterestRate ? div(this.formValidate.freeDayInterestRate, 100) : 0,
            freeServiceFeeRate: this.formValidate.freeServiceFeeRate ? div(this.formValidate.freeServiceFeeRate, 100) : 0,
            status: this.formValidate.status
          }
          if (this.formValidate.rState) {
            data['repetitionLoanNum'] = this.formValidate.repetitionLoanNum
          }
          if (this.formValidate.hState) {
            data['historyOverdueNum'] = this.formValidate.historyOverdueNum
          }
          if (this.formValidate.lState) {
            data['lastNormalSettle'] = this.formValidate.lastNormalSettle
          }
          if (this.formValidate.tState) {
            data['telecomScore'] = this.formValidate.telecomScore
          }
          if (this.formValidate.cState) {
            data['creditScore'] = this.formValidate.creditScore
          }
          if (this.formValidate.dState) {
            data['lastDueDays'] = this.formValidate.lastDueDays
          }
          if (data.id) {
            updateUserLevel(data)
              .then(res => {
                this.submitLoading = false
                if (res.success) {
                  this.$message.success(this.$t('common.tip.editSuccess'))
                  this.$emit('change-dialog', false)
                  this.$emit('edit-success')
                  this.handleClose()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.$message.error(err.message)
                this.submitLoading = false
              })
          } else {
            addUserLevel(data)
              .then(res => {
                this.submitLoading = false
                if (res.success) {
                  this.$message.success(this.$t('common.tip.addSuccess'))
                  this.$emit('change-dialog', false)
                  this.$emit('edit-success')
                  this.handleClose()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.$message.error(err.message)
                this.submitLoading = false
              })
          }
        }
      })
    },
    keyup(data) {
      let value = this.formValidate[data]
      value = value.replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
      value = value.replace(/^\./g, '') // 验证第一个字符是数字
      value = value.replace(/\.{2,}/g, '.') // 只保留第一个, 清除多余的
      value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      const num = value.indexOf('.')
      if (num < 0 && value !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        value = parseFloat(value)
      }
      if (num > -1) { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        let before = value.substring(0, num)
        const after = value.substring(num)
        if (before !== '0') {
          before = parseFloat(before)
          value = before + '' + after
        }
      }
      this.formValidate[data] = value
    }
  }
}
</script>

<style scoped>

</style>
